<template>

  <!-- 搜索表单 -->
  <el-card shadow="hover" class="search-card">
    <el-form :model="searchForm" ref="formRef" label-width="auto" :size="size">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="古树名" prop="chineseName">
            <el-input v-model="searchForm.chineseName" placeholder="请输入查询的中文树名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="科名" prop="familyName">
            <el-input v-model="searchForm.familyName" placeholder="请输入查询科名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="属名" prop="genusName">
            <el-input v-model="searchForm.genusName" placeholder="请输入查询的属名" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="树龄" prop="stimatedAge">
            <el-input-number v-model="searchForm.stimatedAge" :min="0" :controls="false" placeholder="请输入查询的树龄" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="创建时间" prop="dateRange">
            <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="-" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="查询地址" prop="locationAddress">
            <el-input v-model="searchForm.locationAddress" placeholder="请输入查询的地址" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6" class="flex items-center">
          <div class="btns">
            <el-button size="large" icon="Refresh" @click="handleResetClick">重置</el-button>
            <el-button size="large" type="primary" icon="Search" @click="fetchTreeData" :loading="loading">
              查询
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <div class="header-container">
    <h2 class="title">古树信息</h2>
    <el-button type="danger" size="large" icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete"
      style="margin: 10px 20px;">
      批量删除
    </el-button>
  </div>
  <!-- 表格区域 -->
  <el-card shadow="hover" class="mt-4">


    <!-- 表格 -->
    <div class="table-container">
      <el-table :data="treeList" stripe border style="width: 100%" @selection-change="handleSelectionChange"
        v-loading="tableLoading" :height="tableHeight">
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" align="center"></el-table-column>

        <!-- 数据列 -->
        <el-table-column prop="treeId" label="ID" align="center" width="80"></el-table-column>
        <el-table-column prop="chineseName" label="中文名" align="center" width="100"></el-table-column>
        <el-table-column prop="scientificName" label="学名" align="center" width="150"></el-table-column>
        <el-table-column prop="familyName" label="科名" align="center" width="120"></el-table-column>
        <el-table-column prop="genusName" label="属名" align="center" width="120"></el-table-column>
        <el-table-column prop="estimatedAge" label="估计年龄(年)" align="center" width="120"></el-table-column>
        <el-table-column prop="gpsLongitude" label="经度" align="center" width="120"></el-table-column>
        <el-table-column prop="gpsLatitude" label="纬度" align="center" width="120"></el-table-column>
        <el-table-column prop="locationAddress" label="位置地址" align="center" width="200"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="180"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center" width="180"></el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template #default="scope">
            <el-button size="small" type="danger" icon="Delete" @click="handleDelete(scope.row)" plain
              style="margin: 10px 20px;">
              删除
            </el-button><el-button size="small" type="danger" icon="Delete" @click="handleDelete(scope.row)" plain>
              删除
            </el-button>
            <el-button size="small" type="danger" icon="Delete" @click="handleDelete(scope.row)" plain>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 分页 -->
    <div class="pagination-container mt-4">
      <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.pageSize"
        :page-sizes="[5, 10, 15, 30]" :size="size" :disabled="false" background
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { ElForm, ElMessage, ElMessageBox } from 'element-plus'
import type { ComponentSize } from 'element-plus'
import type { AncientTree } from '@/types/response'
import { getTreeInfoPage } from '@/api/tree/treeApi'

const size = ref<ComponentSize>('large')
const tableHeight = ref('500px')
const loading = ref(false)
const tableLoading = ref(false)

// 存储表格数据
const treeList = ref<AncientTree[]>([])

// 定义分页参数
const total = ref(0)

const searchForm = reactive({
  page: 1,
  pageSize: 5,
  chineseName: '',
  familyName: '',
  genusName: '',
  stimatedAge: null as number | null,
  locationAddress: '',
  dateRange: ['', ''],
})

const formRef = ref<InstanceType<typeof ElForm>>()

// 重置表单
function handleResetClick() {
  formRef.value?.resetFields()
  fetchTreeData()
}

// 获取表格数据
const fetchTreeData = async () => {
  try {
    loading.value = true
    tableLoading.value = true

    const result = await getTreeInfoPage(searchForm)
    if (result.code === 1) {
      treeList.value = result.data.records
      total.value = result.data.total
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    ElMessage.error(' 获取数据失败')
     console.log(error)
  } finally {
    loading.value = false
    tableLoading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  fetchTreeData()
})

const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  fetchTreeData()
}

const handleCurrentChange = (val: number) => {
  searchForm.page = val
  fetchTreeData()
}

// 多选时获取选中的项
const selectedRows = ref<number[]>([])
const handleSelectionChange = (rows: AncientTree[]) => {
  selectedRows.value = rows.map(row => row.treeId)
}

// 单个删除
const handleDelete = (row: AncientTree) => {
  ElMessageBox.confirm(` 确定要删除古树【${row.chineseName} 】吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 这里调用删除API
    ElMessage.success(' 删除成功')
    fetchTreeData()
  }).catch(() => {
    ElMessage.info(' 已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(' 请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(` 确定要删除选中的${selectedRows.value.length} 条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 这里调用批量删除API
    ElMessage.success(` 成功删除${selectedRows.value.length} 条记录`)
    selectedRows.value = []
    fetchTreeData()
  }).catch(() => {
    ElMessage.info(' 已取消删除')
  })
}
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.btns {
  display: flex;
  gap: 10px;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  font-weight: bold;
  color: #606266;
}

.el-button--small {
  padding: 5px 10px;
}

.el-button--large {
  padding: 12px 20px;
}

.el-card__header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  margin: 0;
  flex: 1;
  text-align: center;
}
</style>
